import axios, { AxiosResponse } from 'axios';
import { getToken } from '../../utils/authUtils';
import { BASE_URL } from '../../constants/api';

// const BASE_URL = 'http://localhost:8080';

// 消息类型
export type MessageType = {
  id: number;
  fromUserId: number;
  fromUserName: string;
  fromUserAvatar: string;
  toId: number;
  chatType: number;  // 0-私聊, 1-群聊
  content: string;
  contentType: number;  // 0-文本, 1-图片, 2-语音, 3-视频, 4-文件
  status: number;
  createTime: string;
};

// 私聊历史记录返回类型
export type PrivateHistoryResponse = {
  records: MessageType[];
  total: number;
  size: number;
  current: number;
  pages: number;
};

// 好友申请类型
export type FriendRequest = {
  id: number;
  fromUserId: number;
  fromUserName: string;
  fromUserAvatar: string;
  message: string;
  status: number;
  createTime: string;
};

// 好友类型
export type FriendType = {
  friendId: number;
  remark: string;
  userName: string;
  userAvatar: string;
  userProfile: string;
  createTime: string;
};

// 群组类型
export type GroupType = {
  id: number;
  groupName: string;
  avatar: string;
  description: string;
  ownerId: number;
  ownerName: string;
  memberCount: number;
  createTime: string;
  userRole: number; // 0-普通成员, 1-管理员, 2-群主
};

// 群成员类型
export type GroupMemberType = {
  userId: number;
  userName: string;
  userAvatar: string;
  nickname: string;
  role: number;
  joinTime: string;
};

// 配置请求头
const getAuthHeader = async () => {
  const token = await getToken();
  return {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  };
};

// 消息相关API
export const sendMessage = async (toId: number, chatType: number, content: string, contentType: number = 0): Promise<number> => {
  try {
    const response = await axios.post(`${BASE_URL}/api/message/send`, {
      toId,
      chatType,
      content,
      contentType
    }, await getAuthHeader());
    return response.data.data;
  } catch (error) {
    console.error('发送消息失败:', error);
    throw error;
  }
};

// 获取私聊历史记录
export const getPrivateHistory = async (friendId: number, current: number = 1, size: number = 20): Promise<PrivateHistoryResponse> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: PrivateHistoryResponse, message: string}> = 
      await axios.get(`${BASE_URL}/api/message/private/${friendId}?current=${current}&size=${size}`, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取私聊历史记录失败:', error);
    throw error;
  }
};

// 获取群聊历史记录
export const getGroupHistory = async (groupId: number, current: number = 1, size: number = 20): Promise<PrivateHistoryResponse> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: PrivateHistoryResponse, message: string}> = 
      await axios.get(`${BASE_URL}/api/message/group/${groupId}?current=${current}&size=${size}`, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取群聊历史记录失败:', error);
    throw error;
  }
};

// 获取未读消息数量
export const getUnreadCount = async (): Promise<number> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: number, message: string}> = 
      await axios.get(`${BASE_URL}/api/message/unread/count`, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
    throw error;
  }
};

// 标记消息已读
export const markMessagesAsRead = async (messageIds: number[]): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/message/read`, {
        messageIds
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('标记消息已读失败:', error);
    throw error;
  }
};

// 撤回消息
export const recallMessage = async (messageId: number): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/message/recall`, {
        messageId
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('撤回消息失败:', error);
    throw error;
  }
};

// 好友管理相关API
export const searchUserByStudentId = async (studentId: string): Promise<any> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: any, message: string}> = 
      await axios.post(`${BASE_URL}/api/friend/search`, {
        studentId
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    throw error;
  }
};

// 发送好友请求
export const sendFriendRequest = async (toUserId: number, message: string = ''): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/friend/request`, {
        toUserId,
        message
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('发送好友请求失败:', error);
    throw error;
  }
};

// 获取好友申请列表
export const getFriendRequests = async (current: number = 1, size: number = 10): Promise<{records: FriendRequest[], total: number}> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: {records: FriendRequest[], total: number, size: number, current: number, pages: number}, message: string}> = 
      await axios.get(`${BASE_URL}/api/friend/request/list?current=${current}&size=${size}`, config);
    
    if (response.data.code === 0) {
      return {
        records: response.data.data.records,
        total: response.data.data.total
      };
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取好友申请列表失败:', error);
    throw error;
  }
};

// 处理好友申请
export const handleFriendRequest = async (requestId: number, status: number, remark: string = ''): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/friend/handle`, {
        requestId,
        status,
        remark
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('处理好友申请失败:', error);
    throw error;
  }
};

// 获取好友列表
export const getFriendList = async (): Promise<FriendType[]> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: FriendType[], message: string}> = 
      await axios.get(`${BASE_URL}/api/friend/list`, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取好友列表失败:', error);
    throw error;
  }
};

// 删除好友
export const deleteFriend = async (friendId: number): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/friend/delete/${friendId}`, {}, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('删除好友失败:', error);
    throw error;
  }
};

// 修改好友备注
export const updateFriendRemark = async (friendId: number, remark: string): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/friend/remark`, {
        friendId,
        remark
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('修改好友备注失败:', error);
    throw error;
  }
};

// 群组管理相关API
// 创建群组
export const createGroup = async (groupName: string, avatar: string = '', description: string = '', memberIds: number[] = []): Promise<number> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: number, message: string}> = 
      await axios.post(`${BASE_URL}/api/group/create`, {
        groupName,
        avatar,
        description,
        memberIds
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('创建群组失败:', error);
    throw error;
  }
};

// 修改群组信息
export const updateGroupInfo = async (groupId: number, groupName?: string, avatar?: string, description?: string): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const data: any = { groupId };
    
    if (groupName) data.groupName = groupName;
    if (avatar) data.avatar = avatar;
    if (description) data.description = description;
    
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/group/update`, data, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('修改群组信息失败:', error);
    throw error;
  }
};

// 获取用户加入的群组列表
export const getGroupList = async (): Promise<GroupType[]> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: GroupType[], message: string}> = 
      await axios.get(`${BASE_URL}/api/group/list`, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取群组列表失败:', error);
    throw error;
  }
};

// 邀请用户加入群组
export const inviteToGroup = async (groupId: number, userIds: number[]): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/group/invite`, {
        groupId,
        userIds
      }, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('邀请用户加入群组失败:', error);
    throw error;
  }
};

// 获取群成员列表
export const getGroupMembers = async (groupId: number): Promise<GroupMemberType[]> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: GroupMemberType[], message: string}> = 
      await axios.get(`${BASE_URL}/api/group/member/list/${groupId}`, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('获取群成员列表失败:', error);
    throw error;
  }
};

// 退出群组
export const quitGroup = async (groupId: number): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/group/quit/${groupId}`, {}, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('退出群组失败:', error);
    throw error;
  }
};

// 解散群组
export const dismissGroup = async (groupId: number): Promise<boolean> => {
  try {
    const config = await getAuthHeader();
    const response: AxiosResponse<{code: number, data: boolean, message: string}> = 
      await axios.post(`${BASE_URL}/api/group/dismiss/${groupId}`, {}, config);
    
    if (response.data.code === 0) {
      return response.data.data;
    } else {
      throw new Error(response.data.message);
    }
  } catch (error) {
    console.error('解散群组失败:', error);
    throw error;
  }
}; 